package com.example.soapserver.service.impl;

import com.example.soapserver.model.department.*;
import com.example.soapserver.service.DepartmentWebService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.jws.WebService;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 部门WebService服务实现
 */
@Service
@WebService(serviceName = "DepartmentService",
           endpointInterface = "com.example.soapserver.service.DepartmentWebService",
           targetNamespace = "http://com.cssc.cn/webservice/department")
public class DepartmentWebServiceImpl implements DepartmentWebService {

    // 模拟数据存储
    private List<Department> departmentStore = new ArrayList<>();

    @Override
    public ReceiveDeptDataResponse receiveDeptData(ReceiveDeptDataRequest request) {
        ReceiveDeptDataResponse response = new ReceiveDeptDataResponse();
        long startTime = System.currentTimeMillis();
        
        try {
            if (request == null || request.getDeptData() == null) {
                response.setResultCode("ERROR");
                response.setResultMessage("请求数据不能为空");
                return response;
            }
            
            List<Department> departments = request.getDeptData().getORG();
            if (departments == null || departments.isEmpty()) {
                response.setResultCode("ERROR");
                response.setResultMessage("部门数据不能为空");
                return response;
            }
            
            int successCount = 0;
            int failCount = 0;
            
            for (Department dept : departments) {
                try {
                    // 数据验证
                    String validationError = validateDepartment(dept);
                    if (validationError != null) {
                        System.err.println("部门数据验证失败: " + validationError + ", 部门编码: " + dept.getDeptCode());
                        failCount++;
                        continue;
                    }
                    
                    // 处理部门数据
                    processDepartment(dept);
                    
                    // 保存部门数据
                    boolean saveResult = saveDepartment(dept);
                    
                    if (saveResult) {
                        successCount++;
                        System.out.println("成功保存部门: " + dept.getDeptCode() + " - " + dept.getDeptName());
                    } else {
                        failCount++;
                        System.err.println("保存部门失败: " + dept.getDeptCode());
                    }
                    
                } catch (Exception e) {
                    failCount++;
                    System.err.println("处理部门数据异常: " + dept.getDeptCode() + ", 错误: " + e.getMessage());
                }
            }
            
            response.setResultCode("SUCCESS");
            response.setResultMessage("部门数据处理完成");
            response.setSuccessCount(successCount);
            response.setFailCount(failCount);
            response.setProcessTime((System.currentTimeMillis() - startTime) + "ms");
            
            System.out.println("部门数据处理结果: 成功=" + successCount + ", 失败=" + failCount);
            
        } catch (Exception e) {
            response.setResultCode("ERROR");
            response.setResultMessage("系统错误: " + e.getMessage());
            response.setSuccessCount(0);
            response.setFailCount(0);
            response.setProcessTime((System.currentTimeMillis() - startTime) + "ms");
            
            System.err.println("接收部门数据系统异常: " + e.getMessage());
        }
        
        return response;
    }
    
    @Override
    public GetDeptByCodeResponse getDeptByCode(GetDeptByCodeRequest request) {
        GetDeptByCodeResponse response = new GetDeptByCodeResponse();
        
        try {
            if (request == null || !StringUtils.hasText(request.getDeptCode())) {
                response.setResultCode("ERROR");
                response.setResultMessage("部门编码不能为空");
                return response;
            }
            
            String deptCode = request.getDeptCode().trim();
            Department department = findDepartmentByCode(deptCode);
            
            if (department != null) {
                response.setDepartment(department);
                response.setResultCode("SUCCESS");
                response.setResultMessage("查询成功");
                System.out.println("查询部门成功: " + deptCode);
            } else {
                response.setResultCode("NOT_FOUND");
                response.setResultMessage("未找到部门编码为 " + deptCode + " 的部门信息");
                System.out.println("查询部门不存在: " + deptCode);
            }
            
        } catch (Exception e) {
            response.setResultCode("ERROR");
            response.setResultMessage("查询失败: " + e.getMessage());
            System.err.println("查询部门异常: " + e.getMessage());
        }
        
        return response;
    }
    
    @Override
    public GetAllDeptsResponse getAllDepts(GetAllDeptsRequest request) {
        GetAllDeptsResponse response = new GetAllDeptsResponse();
        
        try {
            boolean includeDisabled = request != null && Boolean.TRUE.equals(request.isIncludeDisabled());
            
            List<Department> allDepartments = getAllDepartments(includeDisabled);
            Root root = new Root();
//            root.(allDepartments);
            
            response.setDepartments(root);
            response.setTotalCount(allDepartments.size());
            response.setResultCode("SUCCESS");
            response.setResultMessage("查询成功");
            
            System.out.println("获取所有部门成功: 总数=" + allDepartments.size() + ", 包含禁用=" + includeDisabled);
            
        } catch (Exception e) {
            response.setResultCode("ERROR");
            response.setResultMessage("查询失败: " + e.getMessage());
            System.err.println("获取所有部门异常: " + e.getMessage());
        }
        
        return response;
    }
    
    @Override
    public String testService() {
        String status = "Department WebService服务运行正常\n";
        status += "服务时间: " + new Date() + "\n";
        status += "当前存储部门数量: " + departmentStore.size() + "\n";
        status += "服务状态: ACTIVE";
        
        System.out.println("服务测试调用: " + status);
        return status;
    }
    
    // 数据验证方法
    private String validateDepartment(Department dept) {
        if (!StringUtils.hasText(dept.getDeptCode())) {
            return "部门编码不能为空";
        }
        if (!StringUtils.hasText(dept.getDeptName())) {
            return "部门名称不能为空";
        }
        if (dept.getAccStatus() != null && dept.getAccStatus() != 0 && dept.getAccStatus() != 1) {
            return "数据状态必须是0(禁用)或1(启用)";
        }
        if (dept.getDeptLevel() != null && dept.getDeptLevel() < 1) {
            return "部门层级必须大于0";
        }
        
        // 检查部门编码是否已存在
        if (isDepartmentCodeExists(dept.getDeptCode())) {
            return "部门编码已存在: " + dept.getDeptCode();
        }
        
        return null;
    }
    
    // 处理部门数据
    private void processDepartment(Department dept) {
        // 设置默认值
        if (dept.getAccStatus() == null) {
            dept.setAccStatus(1); // 默认启用
        }
        if (dept.getSortOrder() == null) {
            dept.setSortOrder(999); // 默认排序号
        }
        if (dept.getDeptLevel() == null) {
            // 根据父部门设置层级
            if (!StringUtils.hasText(dept.getParentDeptCode())) {
                dept.setDeptLevel(1); // 根部门
            } else {
                dept.setDeptLevel(2); // 子部门
            }
        }
        
        // 处理父部门名称，确保不为空
        if (dept.getParentDeptName() == null || dept.getParentDeptName().isEmpty()) {
            if (StringUtils.hasText(dept.getParentDeptCode())) {
                dept.getParentDeptName().add("未知部门");
            }
        }
    }
    
    // 保存部门数据
    private boolean saveDepartment(Department dept) {
        try {
            // 模拟保存到数据库
            departmentStore.add(dept);
            return true;
        } catch (Exception e) {
            System.err.println("保存部门到存储失败: " + e.getMessage());
            return false;
        }
    }
    
    // 根据部门编码查找部门
    private Department findDepartmentByCode(String deptCode) {
        return departmentStore.stream()
                .filter(dept -> deptCode.equals(dept.getDeptCode()))
                .findFirst()
                .orElse(null);
    }
    
    // 检查部门编码是否存在
    private boolean isDepartmentCodeExists(String deptCode) {
        return departmentStore.stream()
                .anyMatch(dept -> deptCode.equals(dept.getDeptCode()));
    }
    
    // 获取所有部门
    private List<Department> getAllDepartments(boolean includeDisabled) {
        if (includeDisabled) {
            return new ArrayList<>(departmentStore);
        } else {
            List<Department> activeDepartments = new ArrayList<>();
            for (Department dept : departmentStore) {
                if (dept.getAccStatus() == null || dept.getAccStatus() == 1) {
                    activeDepartments.add(dept);
                }
            }
            return activeDepartments;
        }
    }
}